package cn.marinda.util;

import cn.marinda.entity.Server;
import cn.marinda.gui.impl.TipsDialogImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * http网络请求工具类
 *
 * @author marinda
 * @date 2022/07/11
 */
public class HttpUtils {

//    核心
    public static Server serverEnum;
//    文件名
    public static String fileName;
//    地址
    public static String urlPath;

//    是否下载完毕
    public static boolean downloadFlag;

//    最新插件仓库地址
    public final static String PLUGIN_WARE_HOURSE = "http://175.24.177.189/resource.php?token=test&type=plugin";

//    最新核心仓库地址
    public final static String CORE_WARE_HOURSE = "http://175.24.177.189/resource.php?token=test&type=core";

//    版本仓库地址
    public final static String VERSION_HOURSE = "http://175.24.177.189/resource.php?token=test&type=version";

//    头像仓库地址
    public final static String AUTHOR_PORTRAIT_HOURSE = "http://175.24.177.189/mcAuthor/portrait.jpg";

//    群聊仓库地址
    public final static String AUTHOR_GROUP_HOURSE = "http://175.24.177.189/mcAuthor/group.png";

//    logo仓库地址
    public final static String AUTHOR_LOGO_HOURSE = "http://175.24.177.189/mcAuthor/logo.png";
//    是否是在线插件下载
    public static boolean isOnlineFlag = false;

//    是否是在线核心下载
    public static boolean isOnlineCore = false;

    public static String onlineCoreName = "";

    /**
     * 下载文件
     *
     * @return boolean
     */
    public static boolean downloadFile(){
        try {
            URL url = new URL(urlPath);
            int byteSum = 0;
            int byteRead = 0;
            URLConnection connection = url.openConnection();
            InputStream fileInputStream = connection.getInputStream();
            File file = new File(Server.SERVER_ROOT.getPath()+ serverEnum.getPath(),fileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            while((byteRead = fileInputStream.read(bytes)) > 0){
                int fileSize = connection.getContentLength();
                double result = (float)byteSum / fileSize *100;
                byteSum+=byteRead;
                outputStream.write(bytes,0,byteRead);
            }
            if(!new File(fileName).exists()){
                return false;
            }
            outputStream.close();
            fileInputStream.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
            return false;
        }catch (IOException e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return true;

    }

    /**
     * 加载插件在线文件列表
     *
     * @return {@link List}<{@link String}>
     */
    public static List<String> loadOnlinePluginFiles(){
        Object[] pluginArray = new String[]{};
        List<String> pluginList = new ArrayList<>();
        try {
            URL url = new URL(PLUGIN_WARE_HOURSE);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(5000);
            connection.connect();
//            成功
            if(connection.getResponseCode() == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String str = "";

                while((str = reader.readLine()) != null){
                    JSONArray array = JSON.parseArray(str);
                    pluginArray = array.stream().toArray();
                }

                Arrays.stream(pluginArray).forEach(ele->{
                    pluginList.add(ele.toString());
                });
                reader.close();
            }

        }catch (FileNotFoundException e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();

        }catch (IOException e){
            e.printStackTrace();
        }
        return pluginList;
    }

    /**
     * 加载插件在线文件列表
     *
     * @return {@link List}<{@link String}>
     */
    public static BufferedImage loadAuthorInfo(String info){
        BufferedImage bufferedImage = null;
        try {
            String hourse = "";
            if(info.equalsIgnoreCase("group")){
                hourse = AUTHOR_GROUP_HOURSE;
            }else{
                hourse = AUTHOR_PORTRAIT_HOURSE;
            }
            bufferedImage = ImageIO.read(new URL(hourse));
            return bufferedImage;
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return null;
    }


    /**
     * 加载插件在线文件列表
     *
     * @return {@link List}<{@link String}>
     */
    public static BufferedImage loadLogo(){
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(new URL(AUTHOR_LOGO_HOURSE));
            return bufferedImage;
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return null;
    }

    /**
     * 加载在线核心文件列表
     *
     * @return {@link List}<{@link String}>
     */
    public static List<String> loadOnlineServerCoreFiles(){
        Object[] coreArray = new String[]{};
        List<String> coreList = new ArrayList<>();
        try {
            URL url = new URL(CORE_WARE_HOURSE);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(20000);
            connection.setReadTimeout(5000);
            connection.connect();
//            成功
            if(connection.getResponseCode() == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String str = "";

                while((str = reader.readLine()) != null){
                    JSONArray array = JSON.parseArray(str);
                    coreArray = array.stream().toArray();
                }

                Arrays.stream(coreArray).forEach(ele->{
                    coreList.add(ele.toString());
                });
                reader.close();
            }

        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return coreList;
    }

    /**
     * 加载在线核心文件列表
     *
     * @return {@link List}<{@link String}>
     */
    public static List<String> loadVersion(){
        Object[] coreArray = new String[]{};
        List<String> coreList = new ArrayList<>();
        try {
            URL url = new URL(VERSION_HOURSE);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(5000);
            connection.connect();
//            成功
            if(connection.getResponseCode() == 200){
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String str = "";

                while((str = reader.readLine()) != null){
                    JSONArray array = JSON.parseArray(str);
                    coreArray = array.stream().toArray();
                }

                Arrays.stream(coreArray).forEach(ele->{
                    coreList.add(ele.toString());
                });
                reader.close();
            }

        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return coreList;
    }

    /**
     * 下载文件 带进度条
     *
     * @param progressBar 进度条
     * @return boolean
     */
    public static boolean downloadFile(JProgressBar progressBar){
        try {
            URL url = new URL(urlPath);
            int byteSum = 0;
            int byteRead = 0;
            URLConnection connection = url.openConnection();
            InputStream fileInputStream = connection.getInputStream();
            File file = new File(Server.SERVER_ROOT.getPath()+ serverEnum.getPath(),fileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            while((byteRead = fileInputStream.read(bytes)) > 0){
                int fileSize = connection.getContentLength();
                double result = (float)byteSum / fileSize * 100;
                String progressValue = (new DecimalFormat("#").format(result)) + "%";
                progressBar.setValue((int) Math.round(result));

                byteSum+=byteRead;
                outputStream.write(bytes,0,byteRead);
            }
            if(!file.exists()){
                return false;
            }
            outputStream.close();
            fileInputStream.close();
            return true;
        }catch (Exception e){
            TipsDialogImpl.instance.close();
            TipsDialogImpl.instance.open();
        }
        return true;
    }

    /**
     * 下载文件 带进度条
     *
     * @param progressBar 进度条
     * @return boolean
     */
    public static boolean downloadPlugin(JProgressBar progressBar,Server serverDir,String urlPath){
//        插件列表
        Set<String> pluginList = ServerUtils.serverPluginSet;
        String pluginName;
        String originalUrl = urlPath;
        for(String key : pluginList){
//            如果文件列表中不存在[] 则直接获取名字即可
            if(key.indexOf("[") == -1){
                pluginName = key;
            }else{
                pluginName = ServerUtils.splitStartString(key).concat(".jar");
            }
            urlPath = originalUrl+pluginName;
            try {
                URL url = new URL(urlPath);
                int byteSum = 0;
                int byteRead = 0;
                URLConnection connection = url.openConnection();
                InputStream fileInputStream = connection.getInputStream();
                File file = new File(Server.SERVER_ROOT.getPath()+ serverDir.getPath(),pluginName);
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                while((byteRead = fileInputStream.read(bytes)) > 0){
                    int fileSize = connection.getContentLength();
                    double result = (float)byteSum / fileSize * 100;
                    String progressValue = (new DecimalFormat("#").format(result)) + "%";
                    progressBar.setValue((int) Math.round(result));
                    byteSum+=byteRead;
                    outputStream.write(bytes,0,byteRead);
                }
                if(!file.exists()){
                    return false;
                }
                outputStream.close();
                fileInputStream.close();
            }catch (FileNotFoundException e){
                TipsDialogImpl.instance.close();
                TipsDialogImpl.instance.open();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        return true;
    }
}
